<?php

namespace App\Http\Controllers\Api;

use App\ActivityBargain;
use App\ActivityBargainInitiate;
use App\ActivityBargainJoin;
use App\ActivityGroup;
use App\ActivityGroupAdd;
use App\ActivityGroupPrice;
use App\ActivityGroupRefund;
use App\ChargeAvailable;
use App\Coupons;
use App\DiscountRule;
use App\DiscountSalesRule;
use App\DiscountXGoods;
use App\Exceptions\OrderException;
use App\Express;
use App\ExpressBlade;
use App\ExpressCustomFee;
use App\Goods;
use App\GoodSpu;
use App\GoodsSnapshot;
use App\GoodsSpu;
use App\GoodsSpuShop;
use App\Http\Controllers\DistributionController;
use App\Http\Services\FileManager;
use App\Http\Services\ToolsManager;
use App\Http\Services\UserManager;
use App\OrderAddress;
use App\OrderItem;
use App\OrderRefund;
use App\Orders;
use App\ReturnAddress;
use App\ShopCart;
use App\Shops;
use App\User;
use App\UserAddress;
use App\UserCoupon;
use App\UserInfo;
use App\UserIntegralRecord;
use Illuminate\Contracts\Encryption\EncryptException;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use phpDocumentor\Reflection\DocBlock\Tags\Uses;

class OrderController extends Controller{

    public function buildOrder(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $goodsIds                      = !is_null($request->get('goods_id')) ? $request->get('goods_id') : 0;
        $num                           = !is_null($request->get('num')) && trim($request->get('num')) != "" ? $request->get('num') : 1;
        $type                          = !is_null($request->get('type')) && trim($request->get('type')) != "" ? $request->get('type') : 'goods';
        $remark                        = $request->get('remark');
        $note                          = $request->get('note');
        $goodSpuId                     = $request->get('goods_spu_id');
        $couponId                      = !is_null($request->get('coupon_id')) ? $request->get('coupon_id') : 0;
        $invite_user_id                = $request->get("invite_id");
        $addressId                     = !is_null($request->get('address_id')) ? $request->get('address_id') : 0;
        $pay_type                      = !is_null($request->get('pay_type')) ? $request->get('pay_type') : '';

        if (!in_array($pay_type,['weixin','balance']))
            return response()->json(['level' => 'error','message' => '请选择支付方式','data' =>[]]);
        // TODO 购物车购买
        if($type == 'shop_cart'){
            if(is_array($goodsIds)){
                $generateOrder = DB::transaction(function() use($user,$goodsIds,$remark,$addressId,$couponId,$pay_type){
                    $orderNum = ToolsManager::makeBillNum();
                    while(true){
                        $isOrders = Orders::whereOrderNum($orderNum)->first();
                        if($isOrders){
                            $orderNum = ToolsManager::makeBillNum();
                        }else{
                            break;
                        }
                    }

                    // Todo 记录订单地址
                    $userAddress=UserAddress::whereId($addressId)->whereUserId($user->id)->first();
                    if(!$userAddress)
                        throw new  OrderException(OrderException::AddressNotFound);
                    //TODO sum one goods number
                    $thisGoodsSumNun=[];
                    $freeGoodsList=[];
                    $allGoodsIds=[];
                    $reduce_amount=0;
                    $total_weight=0;
                    foreach($goodsIds as $shop_cart_id){

                        /** @var ShopCart $temp */
                        $temp = ShopCart::whereId($shop_cart_id)->whereUserId($user->id)->first();
                        if ($temp) {
                            if (isset($thisGoodsSumNun['goods_id_' . $temp->goods_id])) {
                                $tmp = $thisGoodsSumNun['goods_id_' . $temp->goods_id];
                                $thisGoodsSumNun['goods_id_' . $temp->goods_id] = $tmp + $temp->num;
                            } else {
                                $thisGoodsSumNun['goods_id_' . $temp->goods_id] = $temp->num;
                            }
                            array_push($allGoodsIds,$temp->goods_id);
                        }
                    }

                    //TODO 遍历统计赠送（满减）数量
                    $allGoodsIds=array_unique($allGoodsIds);
                    if (count($allGoodsIds) > 0){
                        foreach ($allGoodsIds as $item){
                            $free_num=self::getFreeNum($item,$thisGoodsSumNun['goods_id_' . $item],$user->id);
                            $freeGoodsList['free_goods_id'.$item]=$free_num;
                            //$freeGoodsList=['free_goods_id1'=>5]
                            //$freeGoodsList=['free_goods_id*'=>送的数量]
                            $reduce_amount=$reduce_amount + self::getGoodsReduce($item,$thisGoodsSumNun['goods_id_' . $item],$user->id);
                        }
                    }

                    $newOrderAddress=new OrderAddress();
                    $newOrderAddress->consignee  = $userAddress->consignee;
                    $newOrderAddress->province   = $userAddress->province;
                    $newOrderAddress->city       = $userAddress->city;
                    $newOrderAddress->area       = $userAddress->area;
                    $newOrderAddress->address    = $userAddress->add_detail;
                    $newOrderAddress->postcode   = $userAddress->postcode;
                    $newOrderAddress->phone      = $userAddress->phone;
                    $newOrderAddress->telephone  = $userAddress->telephone;
                    $newOrderAddress->save();

                    $newOrder = new Orders();
                    $newOrder->user_id      = $user->id;
                    $newOrder->order_num    = $orderNum;
                    $newOrder->note         = $remark;
//                    $newOrder->pickup_code  = $pickupCode;
                    $newOrder->address_id  = $newOrderAddress->id;
                    $newOrder->type         = 'common';
                    $newOrder->pay_type     = $pay_type;
                    $newOrder->save();
//                    //TODO 遍历生成赠送
//                    $allGoodsIds=array_unique($allGoodsIds);
//                    if (count($allGoodsIds) > 0){
//                        foreach ($allGoodsIds as $item){
//                            $free_num=self::getGoodsFreeNum($item,$thisGoodsSumNun['goods_id_' . $item]);
//                            $reduce_amount=$reduce_amount + self::getGoodsReduce($item,$thisGoodsSumNun['goods_id_' . $item]);
//                            $thisGoodsTMP = Goods::whereId($item)->whereIsShop(1)->first();
//                            if(!$thisGoodsTMP){
//                                throw new OrderException(OrderException::GoodsNotFound);
//                            }
//
//                            //TODO 添加赠送单
//                            if ($free_num > 0){
//                                $freeGoodsSnapshot = new GoodsSnapshot();
//                                $freeGoodsSnapshot->goods_id               = $thisGoodsTMP->id;
//                                $freeGoodsSnapshot->ssn                    = $thisGoodsTMP->ssn;
//                                $freeGoodsSnapshot->name                   = '[赠送]'.$thisGoodsTMP->name.'-随机款式';
//                                $freeGoodsSnapshot->m_price                = $thisGoodsTMP->m_price;
//                                $freeGoodsSnapshot->s_price                = 0;
//                                $freeGoodsSnapshot->thumb_id               = $thisGoodsTMP->thumb_id;
//                                $freeGoodsSnapshot->info                   = $thisGoodsTMP->info;
//                                $freeGoodsSnapshot->sale_count             = $thisGoodsTMP->sale_count;
//                                $freeGoodsSnapshot->type                   = $thisGoodsTMP->type;
//                                $freeGoodsSnapshot->exchange_integral      = $thisGoodsTMP->exchange_integral;
//                                $freeGoodsSnapshot->save();
//
//                                $newFreeOrderItem = new OrderItem();
//                                $newFreeOrderItem->goods_id           = $thisGoodsTMP->id;
//                                $newFreeOrderItem->order_id           = $newOrder->id;
//                                $newFreeOrderItem->item_num           = $newOrder->order_num . '#' . rand(1000,9999);
//                                $newFreeOrderItem->m_price            = $thisGoodsTMP->m_price;
//                                $newFreeOrderItem->s_price            = 0;
//                                $newFreeOrderItem->num                = $free_num;
//                                $newFreeOrderItem->goods_snapshot_id  = $freeGoodsSnapshot->id;
//                                $newFreeOrderItem->goods_spu_id       = 0;
//                                $newFreeOrderItem->save();
//                            }
//                        }
//                    }

                    $discount_info   =self::getDiscountInfo($goodsIds,$user->id);
                    $amountSPrice    = 0;
                    $totalNum        = 0;
                    $goodsInfoArr = array();
                    $isFreeShipping  = 0;
                    $i=0;
                  $goodsInfo = array();
                    foreach($goodsIds as $goodsId){

                        // ToDO 购物车记录
                        /** @var ShopCart $thisShopCart */
                        $thisShopCart = ShopCart::whereId($goodsId)->whereUserId($user->id)->first();

                        if(!$thisShopCart)
                            throw new OrderException(OrderException::ShopCartNotFound);
                        /** @var Goods $thisGoods */

                        $thisGoods = Goods::whereId($thisShopCart->goods_id)->whereIsShop(1)->first();
                        if(!$thisGoods){
                            throw new OrderException(OrderException::GoodsNotFound);
                        }else{
                            //TODO 加销量
                            $thisGoods->sale_count=$thisGoods->sale_count + $thisShopCart->num;
                            $thisGoods->save();
                            $thisGoods->thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);
                        }
                        $total_weight=$total_weight+($thisGoods->weight * $thisShopCart->num);

                        //ToDo 商品属性规格
                        $goodSpu=GoodsSpu::whereId($thisShopCart->goods_spu_id)->whereStatus(1)->first();
                        if(!$goodSpu)
                            throw  new OrderException(OrderException::GoodsNotFound);

                        //ToDo 库存
                        if($thisShopCart->num > $goodSpu->stock)
                            throw new OrderException(OrderException::GoodsStockNotFull);
//                            throw new OrderException(OrderException::GoodsStockNotFull."$thisGoods->name"."$goodSpu->spu_name");

                        //TODO 商品优惠
                        $discount_price=$goodSpu->price * self::getGoodsDiscount($thisGoods->id,$thisGoodsSumNun['goods_id_' . $thisGoods->id],$user->id);
                        //TODO  减库存
                        $goodSpu->stock=$goodSpu->stock - $thisShopCart->num;
                        $goodSpu->save();

                        // ToDo 商品快照
                        $newGoodsSnapshot = new GoodsSnapshot();
                        $newGoodsSnapshot->goods_id               = $thisGoods->id;
                        $newGoodsSnapshot->ssn                    = $thisGoods->ssn;
                        $newGoodsSnapshot->name                   = ($thisGoods->name ? $thisGoods->name : '' ).('-').($goodSpu->size_spu_name ? $goodSpu->size_spu_name : '').('-').($goodSpu->color_spu_name ? $goodSpu->color_spu_name : '').('-').($goodSpu->specification_code ? $goodSpu->specification_code : '');
                        $newGoodsSnapshot->m_price                = $goodSpu->price;
                        $newGoodsSnapshot->s_price                = $discount_price;
                        $newGoodsSnapshot->thumb_id               = $thisGoods->thumb_id;
                        $newGoodsSnapshot->info                   = $thisGoods->info;
                        $newGoodsSnapshot->sale_count             = $thisGoods->sale_count;
                        $newGoodsSnapshot->type                   = $thisGoods->type;
                        $newGoodsSnapshot->exchange_integral      = $thisGoods->exchange_integral;
                        $newGoodsSnapshot->save();

                        array_push($goodsInfo,$newGoodsSnapshot);



                        //ToDo 包邮统计 0：不包邮   1：包邮
                        $isFreeShipping +=$thisGoods->is_free_shipping;
                        $i++;
                       /* $i=array_push($i,$thisGoods->is_free_shipping);*/

                        // ToDo 子订单

                        $newOrderItem = new OrderItem();
                        $newOrderItem->goods_id           = $thisGoods->id;
                        $newOrderItem->order_id           = $newOrder->id;
                        $newOrderItem->item_num           = $newOrder->order_num . '#' . rand(1000,9999);
                        $newOrderItem->m_price            = $goodSpu->price;
                        $newOrderItem->s_price            = (isset($freeGoodsList['free_goods_id'.$thisShopCart->goods_id]) && $freeGoodsList['free_goods_id'.$thisShopCart->goods_id] > 0)
                                                            ? ($freeGoodsList['free_goods_id'.$thisShopCart->goods_id] >= $thisShopCart->num ? 0.00
                                                                : round($discount_price * ($thisShopCart->num - $freeGoodsList['free_goods_id'.$thisShopCart->goods_id]) / $thisShopCart->num,2))
                                                            : $discount_price;
                        $newOrderItem->num                = $thisShopCart->num;
                        $newOrderItem->goods_snapshot_id  = $newGoodsSnapshot->id;
                        $newOrderItem->goods_spu_id       = $goodSpu->id;
                        $newOrderItem->discount_note      = json_encode(self::getDiscountInfoByGoodsId($thisGoods->id,$thisGoodsSumNun['goods_id_' . $thisGoods->id],$user->id));
                        $newOrderItem->save();
                        //TODO 减掉赠送的数量
                        if (isset($freeGoodsList['free_goods_id'.$thisShopCart->goods_id]) && $freeGoodsList['free_goods_id'.$thisShopCart->goods_id] > 0){
                            if ($freeGoodsList['free_goods_id'.$thisShopCart->goods_id] >= $thisShopCart->num){
                                $arrT=$freeGoodsList['free_goods_id'.$thisShopCart->goods_id];
                                $freeGoodsList['free_goods_id'.$thisShopCart->goods_id] = $arrT - $thisShopCart->num;
                            } else {
                                $freeGoodsList['free_goods_id'.$thisShopCart->goods_id] = 0;
                            }
                        } else {
                            $freeGoodsList['free_goods_id'.$thisShopCart->goods_id] = 0;
                        }




                        $amountSPrice += (float)$newOrderItem->s_price * (int)$newOrderItem->num;
                        $totalNum     += $newOrderItem->num;
                        $thisShopCart->delete();

                        $thisGoods->goods_spu_info = $goodSpu;
                        $thisGoods->goods_num      = $thisShopCart->num;

                        array_push($goodsInfoArr,$thisGoods);
                    }

                    $amountSPriceReal=round($amountSPrice-$reduce_amount,2);

                    if($couponId != 0) {
                        /** @var UserCoupon $userCoupon */
                        $userCoupon = UserCoupon::whereId($couponId)->whereIsLocking(0)->whereIsUse(0)->whereUserId($user->id)->first();
                        if(!$userCoupon)
                            throw new OrderException(OrderException::UserCouponNotFound);

                        if(strtotime($userCoupon->end_time) < time())
                            throw  new OrderException(OrderException::CouponNotUse);
                        if($userCoupon->type == 'satisfy'){
                            if ($amountSPriceReal < $userCoupon->satisfy_money)
                                throw  new OrderException(OrderException::OrderAmountNotFull);
                        }

                        $couponAmount=$userCoupon->money;
                        $userCoupon->is_locking=1;
                        $userCoupon->save();
                        $newOrder->coupon_id=$userCoupon->id;
                        $newOrder->save();
                    }else{
                        $couponAmount = 0;
                    }

                    $express=Express::whereIsDefault(1)->first();
                    if(!$express)
                        throw new OrderException(OrderException::ExpressNotFound);

                    //TODO goods sales discount rule process

                    //TODO 余额支付打折
                    $rate=self::balanceDiscount($user->id);
                    $bAmount = ($amountSPriceReal - $couponAmount) * $rate;
                    $wAmount = ($amountSPriceReal - $couponAmount);
                    $expressFeeB=0;
                    $expressFeeW=0;

                    if($isFreeShipping==$i){
                        $expressName=$express->name;
                    }else{
                        $expressName=$express->name;
                        if($express->order_free_shipping_price > $bAmount && $express->order_free_shipping_num > $totalNum) {
                            $expressFeeB =self::getExpressFee($newOrderAddress->province,$totalNum,$total_weight);
                            $expressName = $express->name;
                            $bAmount = $bAmount + $expressFeeB;
                        }

                        if ($express->order_free_shipping_price > $wAmount && $express->order_free_shipping_num > $totalNum){
                            $expressFeeW=self::getExpressFee($newOrderAddress->province,$totalNum,$total_weight);
                            $expressName=$express->name;
                            $wAmount=$wAmount+$expressFeeW;
                        }
                    }

                    $sAmount = $pay_type=='balance' ? $bAmount : $wAmount;
                    if($sAmount <= 0){
                        $sAmount = 0;
                    }
                    $tb=ChargeAvailable::whereUserId($user->id)->first();
                    if ($tb)
                        $rule=DiscountRule::whereId($tb->discount_rule_id)->first();
                    else
                        $rule=null;


                    $newOrder->m_amount      = $amountSPrice; /**   订单原价格 */
                    $newOrder->s_amount      = round($sAmount,2);; /**订单实付价格 */
                    $newOrder->b_amount      = round($bAmount,2);; /**订单余额支付应付价格 */
                    $newOrder->w_amount      = round($wAmount,2);; /**订单微信支付应付价格 */
                    $newOrder->status        = 1;
                    $newOrder->express       = $expressName;
                    $newOrder->express_fee_w = $expressFeeW;
                    $newOrder->express_fee_b = $expressFeeB;
                    $newOrder->express_fee   = $pay_type=='balance' ? $expressFeeB : $expressFeeW;
                    $newOrder->discount_note = json_encode($discount_info);
                    $newOrder->vip_discount_note = $rule ? $rule->rule_name :'无';
                    $newOrder->vip_discount_rate = $rule ? $rule->rate : 1 ;
                    $newOrder->save();

                    if($newOrder->s_amount <= 0){
                        $newOrder->is_pay = 1;
                        $newOrder->pay_time = date("Y-m-d H:i:s",time());
                        $newOrder->status = 2;
                        $newOrder->save();

                        if($couponId != 0) {
                            $userCoupon->is_use = 1;
                            $userCoupon->save();
                        }
                    }
                    return $newOrder;
                });
            }else{
                return response()->json(['level' => 'error','message' => '数据格式错误']);
            }
        }
        elseif($type == 'goods'){
            // TODO 非购物车购买
            $generateOrder = DB::transaction(function() use($goodsIds,$user,$num,$note,$goodSpuId,$addressId,$couponId,$pay_type){
                /** @var Goods $thisGoods */
                $thisGoods = Goods::whereId($goodsIds)->whereIsShop(1)->first();
                if(!$thisGoods){
                    throw new OrderException(OrderException::GoodsNotFound);
                }else{
                    //TODO 加销量
                    $thisGoods->sale_count=$thisGoods->sale_count + $num;
                    $thisGoods->save();
                    $thisGoods->thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);
                }
                $total_weight= $num  * $thisGoods->weight;

                $orderNum = ToolsManager::makeBillNum();
                while(true){
                    $isOrders = Orders::whereOrderNum($orderNum)->first();
                    if($isOrders){
                        $orderNum = ToolsManager::makeBillNum();
                    }else{
                        break;
                    }
                }

                // Todo 记录订单地址
                $userAddress=UserAddress::whereId($addressId)->whereUserId($user->id)->first();
                if(!$userAddress)
                    throw new  OrderException(OrderException::AddressNotFound);

                /*                    $newOrderAddress=self::generateOrderAddress($userAddress);*/

                $newOrderAddress=new OrderAddress();
                $newOrderAddress->consignee  = $userAddress->consignee;
                $newOrderAddress->province   = $userAddress->province;
                $newOrderAddress->city       = $userAddress->city;
                $newOrderAddress->area       = $userAddress->area;
                $newOrderAddress->address    = $userAddress->add_detail;
                $newOrderAddress->postcode   = $userAddress->postcode;
                $newOrderAddress->phone      = $userAddress->phone;
                $newOrderAddress->telephone  = $userAddress->telephone;
                $newOrderAddress->save();

                //TODO 生成订单
                $newOrder = new Orders();
                $newOrder->user_id     = $user->id;
                $newOrder->order_num   = $orderNum;
                $newOrder->type        = $thisGoods->type;
                $newOrder->note        = $note;
                $newOrder->address_id  = $newOrderAddress->id;
                $newOrder->pay_type    = $pay_type;
//                $newOrder->pickup_code = $pickupCode;
                $newOrder->save();

                  //TODO 生成子订单
                $newOrderItem = new OrderItem();
                $newOrderItem->goods_id            = $thisGoods->id;
                $newOrderItem->order_id           = $newOrder->id;
                $newOrderItem->item_num           = $newOrder->order_num . '#' . rand(1000,9999);
                $newOrderItem->num                = $num;
                $newOrderItem->type               = $thisGoods->type;
                $newOrderItem->discount_note      = json_encode(self::getDiscountInfoByGoodsId($thisGoods->id,$num,$user->id));
                $newOrderItem->save();

                $amountSPrice=round((float)$newOrderItem->s_price * (int)$newOrderItem->num,2);

                if($thisGoods->type=="common") {

                    //ToDo 商品属性规格
                    /** @var GoodsSpu $goodSpu */
                    $goodSpu = GoodsSpu::whereId($goodSpuId)->whereGoodsId($thisGoods->id)->whereStatus(1)->first();
                    if (!$goodSpu)
                        throw  new OrderException(OrderException::GoodsNotFound);

                    //ToDo 库存
                    if($num > $goodSpu->stock)
                        throw new OrderException(OrderException::GoodsStockNotFull);
//                    $discount_price =$goodSpu->price * self::getGoodsDiscount($thisGoods->id,$num) - self::getGoodsReduce($thisGoods->id,$num);
                    $discount_price =$goodSpu->price * self::getGoodsDiscount($thisGoods->id,$num,$user->id);
                    $free_num       = self::getFreeNum($thisGoods->id,$num,$user->id);
                    $reduce_amount  =self::getGoodsReduce($thisGoods->id,$num,$user->id);
                    $newGoodsSnapshot = new GoodsSnapshot();
                    $newGoodsSnapshot->goods_id               = $thisGoods->id;
                    $newGoodsSnapshot->ssn                    = $thisGoods->ssn;
                    $newGoodsSnapshot->name                   = ($thisGoods->name ? $thisGoods->name : '' ).('-').($goodSpu->size_spu_name ? $goodSpu->size_spu_name : '').('-').($goodSpu->color_spu_name ? $goodSpu->color_spu_name : '').('-').($goodSpu->specification_code ? $goodSpu->specification_code : '');
                    $newGoodsSnapshot->m_price                = $thisGoods->m_price;
                    $newGoodsSnapshot->s_price                = (isset($free_num) && $free_num > 0) ? ($free_num >= $num ? 0.00 : round($discount_price * ($num - $free_num) / $num,2))
                                                                                                    : $discount_price;
                    $newGoodsSnapshot->thumb_id               = $thisGoods->thumb_id;
                    $newGoodsSnapshot->info                   = $thisGoods->info;
                    $newGoodsSnapshot->sale_count             = $thisGoods->sale_count;
                    $newGoodsSnapshot->type                   = $thisGoods->type;
                    $newGoodsSnapshot->exchange_integral      = $thisGoods->exchange_integral;
                    $newGoodsSnapshot->save();

                    $newOrderItem->goods_snapshot_id  = $newGoodsSnapshot->id;
                    $newOrderItem->m_price            = $goodSpu->price;
                    $newOrderItem->s_price            = (isset($free_num) && $free_num > 0)
                        ? ($free_num >= $num ? 0.00 : round($discount_price * ($num - $free_num) / $num,2))
                        : $discount_price;
                    $newOrderItem->goods_spu_id       = $goodSpu->id;
                    $newOrder->status       = 1;
                    $newOrderItem->save();

//                    //TODO 添加赠送单
//                    if ($free_num > 0){
//                        $newFreeGoodsSnapshot = new GoodsSnapshot();
//                        $newFreeGoodsSnapshot->goods_id               = $thisGoods->id;
//                        $newFreeGoodsSnapshot->ssn                    = $thisGoods->ssn;
//                        $newFreeGoodsSnapshot->name                   = '[赠送]'.(($thisGoods->name ? $thisGoods->name : '' ).('-').($goodSpu->size_spu_name ? $goodSpu->size_spu_name : '').('-').($goodSpu->color_spu_name ? $goodSpu->color_spu_name : '').('-').($goodSpu->specification_code ? $goodSpu->specification_code : ''));
//                        $newFreeGoodsSnapshot->m_price                = $thisGoods->m_price;
//                        $newFreeGoodsSnapshot->s_price                = 0;
//                        $newFreeGoodsSnapshot->thumb_id               = $thisGoods->thumb_id;
//                        $newFreeGoodsSnapshot->info                   = $thisGoods->info;
//                        $newFreeGoodsSnapshot->sale_count             = $thisGoods->sale_count;
//                        $newFreeGoodsSnapshot->type                   = $thisGoods->type;
//                        $newFreeGoodsSnapshot->exchange_integral      = $thisGoods->exchange_integral;
//                        $newFreeGoodsSnapshot->save();
//
//                        $newFreeOrderItem = new OrderItem();
//                        $newFreeOrderItem->goods_id           = $thisGoods->id;
//                        $newFreeOrderItem->order_id           = $newOrder->id;
//                        $newFreeOrderItem->item_num           = $newOrder->order_num . '#' . rand(1000,9999);
//                        $newFreeOrderItem->m_price            = $goodSpu->price;
//                        $newFreeOrderItem->s_price            = 0;
//                        $newFreeOrderItem->num                = $free_num;
//                        $newFreeOrderItem->goods_snapshot_id  = $newFreeGoodsSnapshot->id;
//                        $newFreeOrderItem->goods_spu_id       = $goodSpu->id;
//                        $newFreeOrderItem->save();
//                    }


                    //TODO  减库存
                    $goodSpu->stock=$goodSpu->stock - $num;
                    $goodSpu->save();

                    $amountSPrice=round((float)$newOrderItem->s_price * (int)$newOrderItem->num - $reduce_amount,2);
//                    $amountMMMMM=round((float)$newOrderItem->s_price * (int)$newOrderItem->num,2);
                }
                $amountMMMMM=round((float)$newOrderItem->s_price * (int)$newOrderItem->num,2);
                $discount_info=self::getDiscountInfoByGoodsId($goodsIds,$num,$user->id);

                if($couponId != 0) {
                    /** @var UserCoupon $userCoupon */
                    $userCoupon = UserCoupon::whereId($couponId)->whereIsLocking(0)->whereIsUse(0)->whereUserId($user->id)->first();
                    if(!$userCoupon)
                        throw new OrderException(OrderException::UserCouponNotFound);

                    if(strtotime($userCoupon->end_time) < time())
                        throw  new OrderException(OrderException::CouponNotUse);
                    if($userCoupon->type == 'satisfy'){
                        if ($amountSPrice < $userCoupon->satisfy_money)
                            throw  new OrderException(OrderException::OrderAmountNotFull);
                    }

                    $couponAmount=$userCoupon->money;
                    $userCoupon->is_locking=1;
                    $userCoupon->save();
                    $newOrder->coupon_id=$userCoupon->id;
                    $newOrder->save();
                }else{
                    $couponAmount = 0;
                }

                $express=Express::whereIsDefault(1)->first();
                if(!$express)
                    throw new OrderException(OrderException::ExpressNotFound);

                //TODO 会员打折
                $rate=self::balanceDiscount($user->id);
                $bAmount = ($amountSPrice - $couponAmount) * $rate;
                $wAmount = ($amountSPrice - $couponAmount);
                $expressFeeB=0;
                $expressFeeW=0;
//                }

                /** 是否包邮 */
//                if($thisGoods->is_free_shipping == 1){
//                    $expressFee=0;
//                    $expressName = $express->name;
//                }else{
//                    if($express->order_free_shipping_price <= $sAmount || $express->order_free_shipping_num <=$num){
//                        $expressFee = 0;
//                        $expressName = $express->name;
//                    }else{
//                        $expressFee = $express->fee;
//                        $expressName = $express->name;
//                    }
//                }

                if($thisGoods->is_free_shipping == 1){
                    $expressName=$express->name;
                }else{
                    $expressName=$express->name;
                    if($express->order_free_shipping_price > $bAmount && $express->order_free_shipping_num > $num) {
                        $expressFeeB = self::getExpressFee($newOrderAddress->province,$num,$total_weight);
                        $expressName = $express->name;
                        $bAmount = $bAmount + $expressFeeB;
                    }

                    if ($express->order_free_shipping_price > $wAmount && $express->order_free_shipping_num > $num){
                        $expressFeeW=self::getExpressFee($newOrderAddress->province,$num,$total_weight);
                        $expressName=$express->name;
                        $wAmount=$wAmount+$expressFeeB;
                    }
                }

                $sAmount = $pay_type=='balance' ? $bAmount : $wAmount;


//                $sAmount = $amountSPrice - $couponAmount + $expressFee;
                if($sAmount <= 0){
                    $sAmount = 0;
                }
                $tb=ChargeAvailable::whereUserId($user->id)->first();
                if ($tb)
                    $rule=DiscountRule::whereId($tb->discount_rule_id)->first();
                else
                    $rule=null;

                $newOrder->m_amount     =  $amountMMMMM;  /**@订单原价格*/
                $newOrder->s_amount     =  round($sAmount,2); /**@订单实付价格*/
                $newOrder->b_amount      = round($bAmount,2);; /**订单余额支付应付价格 */
                $newOrder->w_amount      = round($wAmount,2);; /**订单微信支付应付价格 */
                $newOrder->express_fee_w = $expressFeeW;
                $newOrder->express_fee_b = $expressFeeB;
                $newOrder->express_fee   = $pay_type=='balance' ? $expressFeeB : $expressFeeW;
                $newOrder->express      =  $expressName;
                $newOrder->discount_note = json_encode($discount_info);
                $newOrder->vip_discount_note = $rule ? $rule->rule_name : '无';
                $newOrder->vip_discount_rate = $rule ? $rule->rate : 1 ;
                $newOrder->save();

                if($newOrder->s_amount <= 0){
                    $newOrder->is_pay = 1;
                    $newOrder->pay_time = date("Y-m-d H:i:s",time());
                    $newOrder->status = 2;
                    $newOrder->save();

                    if($couponId != 0) {
                        $userCoupon->is_use = 1;
                        $userCoupon->save();
                    }
                }

                return $newOrder;
            });
        }
        else{
            return response()->json(['level' => 'error','message' => '订单类型不正确']);
        }

        //TODO 记录分享人
        if ($invite_user_id)
            DistributionController::joinMyTeam($user->id,$invite_user_id);

        if($generateOrder->s_amount <= 0)
            return response()->json(['level' => 'paying','message' => '支付成功','data' => $generateOrder]);

        return response()->json(['level' => 'success','message' => '订单生成成功','data' => $generateOrder]);
    }

    public function getOrders(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
//        if(!$user)
//            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $user_id=$user ? $user->id :0;

        $orderNum = $request->get('order_num');

        /** @var Orders $thisOrder */
        $thisOrder = Orders::whereOrderNum($orderNum)->first();
        if(!$thisOrder)
            return response()->json(['level' => 'error','message' => '订单不存在']);

        if($thisOrder->status == 1 && (strtotime($thisOrder->created_at) + (30 * 60)) < time()){
            $thisOrder->status = 6;
            $thisOrder->save();

            /** @var UserCoupon $thisCoupon */
            $thisCoupon = UserCoupon::whereId($thisOrder->coupon_id)->first();
            if($thisCoupon){
                $thisCoupon->is_locking = 0;
                $thisCoupon->save();
            }
        }

        /** @var OrderItem $orderItem */
        $orderItems = OrderItem::whereOrderId($thisOrder->id)->get();
        if(count($orderItems) > 0){
            foreach($orderItems as $orderItem){
                /** @var Goods $thisGoods */
                $thisGoods = GoodsSnapshot::whereId($orderItem->goods_snapshot_id)->first();
                if($thisGoods){
                    $thisGoods->thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);
                }

                $thisGoodsSpu = GoodsSpu::whereId($orderItem->goods_spu_id)->whereGoodsId($orderItem->goods_id)->first();

                $orderItem->goods_info     = $thisGoods;
                $orderItem->goods_spu_info = $thisGoodsSpu;
            }
        }

        if($thisOrder->status == 1){
            $thisOrder->statusType = '待付款';
        }elseif($thisOrder->status == 2){
            $thisOrder->statusType = '待发货';
        }elseif($thisOrder->status == 3){
            $thisOrder->statusType = '待收货';
        }elseif($thisOrder->status == 4){
            $thisOrder->statusType = '待评价';
        }elseif($thisOrder->status == 5){
            $thisOrder->statusType = '已完成';
        }elseif($thisOrder->status == 6){
            $thisOrder->statusType = '已取消';
        }elseif($thisOrder->status == 7){
            $thisOrder->statusType = '售后';
        }elseif($thisOrder->status == 8){
            $thisOrder->statusType = '售后完成';
        }

        $thisOrder->goods_amount    = $thisOrder->s_amount - ($thisOrder->pay_type=='balance' ? $thisOrder->express_fee_b : $thisOrder->express_fee_w);
        $thisOrder->order_item      = $orderItems;
        $thisOrder->amount          = $thisOrder->s_amount;
        $thisOrder->discount_note   = json_decode($thisOrder->discount_note);
        $thisOrder->remark          = $thisOrder->note;
        $thisOrder->order_address   = OrderAddress::whereId($thisOrder->address_id)->first();
        $thisOrder->refund_info     = OrderRefund::whereUserId($user_id)->whereOrderNum($thisOrder->order_num)->orderBy('id','desc')->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $thisOrder]);
    }

    public function getUserAllOrders(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 20;
        $page  = !is_null($request->get('page')) ? $request->get('page') : 1;
        $status = !is_null($request->get('status')) ? $request->get('status') : 0;

        /** @var Orders $allOrder*/
        if($status != '' && $status != 0){
            $allOrders = Orders::whereUserId($user->id)->whereStatus($status)->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        }else{
            $allOrders = Orders::whereUserId($user->id)->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        }

        if(count($allOrders) > 0){
            foreach($allOrders as $allOrder){
                if($allOrder->type == 'group'){
                    if($allOrder->is_pay == 0){
                        $allOrder->delete();
                    }
                }
            }

            foreach($allOrders as $allOrder){
                if($allOrder->status == 1 && (strtotime($allOrder->created_at) + (30 * 60)) < time()){
                    $allOrder->status = 6;
                    $allOrder->save();

                    /** @var UserCoupon $thisCoupon */
                    $thisCoupon = UserCoupon::whereId($allOrder->coupon_id)->first();
                    if($thisCoupon){
                        $thisCoupon->is_locking = 0;
                        $thisCoupon->save();
                    }
                }

                /** @var OrderItem $orderItem */
                $orderItems = OrderItem::whereOrderId($allOrder->id)->orderBy('created_at','desc')->get();
                if(count($orderItems) > 0){
                    foreach($orderItems as $orderItem){
                        /** @var GoodsSnapshot $thisGoods */
                        $thisGoods = GoodsSnapshot::whereId($orderItem->goods_snapshot_id)->first();
                        if($thisGoods){
                            $thisGoods->thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);
                        }

                        $thisGoodsSpu = GoodsSpu::whereId($orderItem->goods_spu_id)->whereGoodsId($orderItem->goods_id)->whereStatus(1)->first();

                        $orderItem->goods_spu_info = $thisGoodsSpu;
                        $orderItem->goods_info     = $thisGoods;
                    }
                }

                if($allOrder->status == 1){
                    $allOrder->statusType = '待付款';
                }elseif($allOrder->status == 2){
                    $allOrder->statusType = '待发货';
                }elseif($allOrder->status == 3){
                    $allOrder->statusType = '待收货';
                }elseif($allOrder->status == 4){
                    $allOrder->statusType = '待评价';
                }elseif($allOrder->status == 5){
                    $allOrder->statusType = '已完成';
                }elseif($allOrder->status == 6){
                    $allOrder->statusType = '已取消';
                }elseif($allOrder->status == 7){
                    $allOrder->statusType = '售后';
                }elseif($allOrder->status == 8){
                    $allOrder->statusType = '售后完成';
                }


                $allOrder->order_item = $orderItems;
                $allOrder->refund_info  = OrderRefund::whereUserId($user->id)->whereOrderNum($allOrder->order_num)->orderBy('id','desc')->first();
            }
        }

        $orderNumber     = Orders::whereUserId($user->id)->count();
        $PendingPayment  = Orders::whereUserId($user->id)->whereStatus(1)->count();
        $toBeDelivered   = Orders::whereUserId($user->id)->whereStatus(2)->count();
        $PendingReceipt  = Orders::whereUserId($user->id)->whereStatus(3)->count();
        $pendingSharing  = Orders::whereUserId($user->id)->whereStatus(4)->count();


        return response()->json([
            'level' => 'success',
            'message' => '获取成功',
            'data' => $allOrders,
            'order_number' => $orderNumber,
            'Pending_payment' => $PendingPayment,
            'to_be_delivered' => $toBeDelivered,
            'Pending_receipt' => $PendingReceipt,
            'pending_sharing' => $pendingSharing
        ]);
    }

    public function cancelOrder(Request $request){
        $type = !is_null($request->get('type')) ? $request->get('type') : 'app';

        if($type == 'app'){
            /** @var User $user */
            $user = UserManager::isLogin($request);
            if(!$user)
                return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);
        }

        $orderNum = !is_null($request->get('order_num')) ? $request->get('order_num') : '';

        /** @var Orders $orders */
        $orders = Orders::whereOrderNum($orderNum)->first();
        if(!$orders || ($orders && $orders->status == 6) || ($orders && $orders->status == 5))
            return response()->json(['level' => 'error','message' => '该订单不存在或已取消']);

        if($orders->status != 1)
            return response()->json(['level' => 'error','message' => '无法取消']);

        $orders->status = 6;
        $orders->save();

        /** @var UserCoupon $thisCoupon */
        $thisCoupon = UserCoupon::whereId($orders->coupon_id)->first();
        if($thisCoupon){
            $thisCoupon->is_locking = 0;
            $thisCoupon->save();
        }

        return response()->json(['level' => 'success','message' => '订单取消成功','data' => $orders]);
    }

    public static function generateGoodsSnapshot(Goods $thisGoods,GoodsSpu $thisGoodsSpu = null){
        $newGoodsSnapshot = new GoodsSnapshot();
        $newGoodsSnapshot->goods_id               = $thisGoods->id;
        $newGoodsSnapshot->ssn                    = $thisGoods->ssn;
//        $newGoodsSnapshot->name                   = $thisGoods->name;
        $newGoodsSnapshot->name                   = $thisGoods->name.'-'.$thisGoodsSpu->size_spu_name.$thisGoodsSpu->color_spu_name.$thisGoodsSpu->specification_code;
//        if(!is_null($thisGoodsSpu)){
//            $newGoodsSnapshot->goods_spu_name         = $thisGoodsSpu->size_spu_name.'-'.$thisGoodsSpu->color_spu_name.;
//        }
        $newGoodsSnapshot->m_price                = $thisGoods->m_price;
        $newGoodsSnapshot->s_price                = $thisGoods->s_price;
        $newGoodsSnapshot->thumb_id               = $thisGoods->thumb_id;
        $newGoodsSnapshot->integral               = $thisGoods->integral;
        $newGoodsSnapshot->info                   = $thisGoods->info;
        $newGoodsSnapshot->sale_count             = $thisGoods->sale_count;
        $newGoodsSnapshot->type                   = $thisGoods->type;
        $newGoodsSnapshot->exchange_integral      = $thisGoods->exchange_integral;
        $newGoodsSnapshot->save();
        return $newGoodsSnapshot;
    }

    /**
     * 使用优惠券
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function useCoupon(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $couponId    = !is_null($request->get('coupon_id')) ? $request->get('coupon_id') : 0;
        $goodsId     = $request->get('goods_id');
        $num         = $request->get('num');
        $goodsSpuId  = !is_null($request->get('goods_spu_id')) ? $request->get('goods_spu_id') : 0;
        $type        = !is_null($request->get('type')) && $request->get('type') != '' ? $request->get('type') : 'goods';

        /** @var UserCoupon $thisUserCoupon */
        $thisUserCoupon = UserCoupon::whereCouponId($couponId)->whereUserId($user->id)->first();
        if(!$thisUserCoupon)
            return response()->json(['level' => 'error','message' => '您没有该优惠券!']);

        if($thisUserCoupon->is_use == 1)
            return response()->json(['level' => 'error','message' => '该优惠券已使用']);

        if(strtotime($thisUserCoupon->end_time) <= time())
            return response()->json(['level' => 'error','message' => '该优惠券已过期']);

        if($thisUserCoupon->is_locking == 1)
            return response()->json(['level' => 'error','message' => '优惠券已被锁定']);

        if($type == 'goods'){
            /** @var Goods $thisGoods */
            $thisGoods = Goods::whereId($goodsId)->whereIsShop(1)->first();
            if(!$thisGoods)
                return response()->json(['level' => 'error','message' => '该商品已下架']);

            /** @var GoodsSpu $thisGoodsSpu */
            $thisGoodsSpu = GoodsSpu::whereId($goodsSpuId)->whereGoodsId($thisGoods->id)->whereStatus(1)->first();
            if(!$thisGoodsSpu)
                return response()->json(['level' => 'error','message' => '商品属性不存在']);

            if($thisGoodsSpu->stock < $num || $thisGoodsSpu->stock == 0)
                return response()->json(['level' => 'error','message' => '商品库存不足']);

            /** @var Express $express */
            $express = Express::whereIsDefault(1)->first();
            if(!$express)
                return response()->json(['level' => 'error','message' => '未找到快递公司']);

            if($thisUserCoupon->type == 'direct'){
                $goodsMoneyTotal = round((float)$thisGoodsSpu->price * (int)$num - (float)$thisUserCoupon->money,2);
            }else{
                if($thisUserCoupon->satisfy_money > round((float)$thisGoodsSpu->price * (int)$num,2))
                    return response()->json(['level' => 'error','message' => '未达到优惠券使用要求']);

                $goodsMoneyTotal = round((float)$thisGoodsSpu->price * (int)$num - (float)$thisUserCoupon->money,2);
            }

            if($thisGoods->is_free_shipping == 1){
                $goodsMoney = $goodsMoneyTotal;
            }else{
                $goodsMoney = (float)$goodsMoneyTotal + (float)$express->fee;
            }


        }else{
            if(!is_array($goodsId))
                return response()->json(['level' => 'error','message' => '数据格式错误！']);

            $goodsMoneyTotal = 0;
            $goodsNum = count($goodsId);
            $isFreeShipping = 0;

            if(count($goodsId) > 0){
                foreach($goodsId as $goodId){
                    /** @var Goods $thisGoods */
                    $thisGoods = Goods::whereId($goodId['good_id'])->whereIsShop(1)->first();
                    if(!$thisGoods)
                        return response()->json(['level' => 'error','message' => '商品已下架,请重新下单']);

                    /** @var GoodsSpu $thisGoodsSpu */
                    $thisGoodsSpu = GoodsSpu::whereId($goodId['goods_spu_id'])->whereGoodsId($thisGoods->id)->whereStatus(1)->first();
                    if(!$thisGoodsSpu)
                        return response()->json(['level' => 'error','message' => '商品属性不存在，请重新下单']);

                    if($thisGoods->is_free_shipping ==1)
                        $isFreeShipping += 1;

                    $goodsMoneyTotal += round((float)$thisGoodsSpu->price * (int)$goodId['num'],2);
                }
            }

            /** @var Express $express */
            $express = Express::whereIsDefault(1)->first();
            if(!$express)
                return response()->json(['level' => 'error','message' => '未找到快递公司']);

            if($thisUserCoupon->type == 'direct'){
                if($goodsNum == $isFreeShipping){
                    $goodsMoney = (float)$goodsMoneyTotal - (float)$thisUserCoupon->money;
                }else{
                    $goodsMoney = round((float)$goodsMoneyTotal - (float)$thisUserCoupon->money + (float)$express->fee,2);
                }
            }else{
                if($thisUserCoupon->satisfy_money > $goodsMoneyTotal)
                    return response()->json(['level' => 'error','message' => '未达到优惠券使用要求']);

                if($goodsNum == $isFreeShipping){
                    $goodsMoney = (float)$goodsMoneyTotal - (float)$thisUserCoupon->money;
                }else{
                    $goodsMoney = round((float)$goodsMoneyTotal - (float)$thisUserCoupon->money + (float)$express->fee,2);
                }
            }
        }

        $result['coupon_money'] = $thisUserCoupon->money;
        $result['goods_money'] = $goodsMoney >= 0 ? $goodsMoney : 0.00;

        return response()->json(['level' => 'success','message' => '优惠成功','data' => $result]);
    }


    /**
     * 提交订单信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function submitOrder(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $goodsIds   = !is_null($request->get('goods_id')) ? $request->get('goods_id') : 0;
        $num        = !is_null($request->get('num')) && trim($request->get('num')) != "" ? $request->get('num') : 1;
        $type       = !is_null($request->get('type')) && trim($request->get('type')) != "" ? $request->get('type') : 'goods';
        $goodsSpuId = !is_null($request->get('goods_spu_id')) && $request->get('goods_spu_id') != '' ? $request->get('goods_spu_id') : 0;
        $address_id = !is_null($request->get('address_id')) ? $request->get('address_id') : 0;

        if($type == 'goods'){
            /** @var Goods $thisGoods */
            $thisGoods = Goods::whereId($goodsIds)->whereIsShop(1)->first();
            if(!$thisGoods)
                return response()->json(['level' => 'error','message' => '该商品已下架']);

            if($thisGoods->type == 'common'){
                /** @var GoodsSpu $thisGoodsSpu */
                $thisGoodsSpu = GoodsSpu::whereId($goodsSpuId)->whereGoodsId($thisGoods->id)->whereStatus(1)->first();
                if(!$thisGoodsSpu)
                    return response()->json(['level' => 'error','message' => '商品属性不存在']);
                if($thisGoodsSpu->stock < $num || $thisGoodsSpu->stock == 0)
                    return response()->json(['level' => 'error','message' => '商品库存不足']);
                /** @var Express $express */
                $express = Express::whereIsDefault(1)->first();
                if(!$express)
                    return response()->json(['level' => 'error','message' => '未找到快递公司']);

                $free_num=self::getFreeNum($thisGoods->id,$num,$user->id);
                $reduce_amount=self::getGoodsReduce($thisGoods->id,$num,$user->id);
                $discount_price=$thisGoodsSpu->price * self::getGoodsDiscount($thisGoods->id,$num,$user->id);


//                $goodsTotalAmount = round((float)$thisGoodsSpu->price * (int)$num * self::getGoodsDiscount($thisGoods->id,(int)$num) - self::getGoodsReduce($thisGoods->id,(int)$num),2);
                $thisGoods->goods_spu_info = $thisGoodsSpu;

            } else {
                return response()->json(['level' => 'error','message' => '系统错误']);
            }
            $tmp_price =($free_num > 0) ? ($free_num >= $num ? 0.00 : round($discount_price * ($num - $free_num )/ $num,2)) : $discount_price;
            $thisGoods->thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);
            $thisGoods->goods_num = $num;
            $discount_info              = self::getDiscountInfoByGoodsId($thisGoods->id,$num,$user->id);
            $thisGoods->discount_name  = count($discount_info['name']) > 0 ? $discount_info['name'] : ['无优惠'];

            $goodsTotalAmount = round( $tmp_price * $num - $reduce_amount,2);

            $total_weight= $num  * $thisGoods->weight;
            $result['goods_info']         = [$thisGoods];
            $goodsAmount = round((float)$thisGoodsSpu->price * (int)$num,2);
            $result['goods_amount']       = $goodsAmount;
            $result['express_company']    = $express->name;
            $address=UserAddress::whereId($address_id)->first();
            if($thisGoods->is_free_shipping == 1){
                $result['express_fee']    = '包邮';
                $result['express_fee_balance']    = '包邮';
                $result['goods_total_amount'] =  round((float)$goodsTotalAmount,2);
                $result['goods_total_amount_balance'] = round($goodsTotalAmount * self::balanceDiscount($user->id),2);
            }else{
                if($express->order_free_shipping_price <= $goodsTotalAmount || $express->order_free_shipping_num <= $num){
                    $result['express_fee']    = '包邮';
                    $result['goods_total_amount'] =  round((float)$goodsTotalAmount,2);
                }else{
//                    $expressFee=$address ? self::getExpressFee($address->province,$num) : $express->fee;
                    $expressFee=$address ? self::getExpressFee($address->province,$num,$total_weight) : $express->fee;
                    $result['express_fee']    = $expressFee;
//                    $result['goods_total_amount'] = round((float)$goodsTotalAmount + (float)$expressFee,2);
                    $result['goods_total_amount'] = round((float)$goodsTotalAmount,2);
                }

                if ($express->order_free_shipping_price <= $goodsTotalAmount * self::balanceDiscount($user->id) || $express->order_free_shipping_num <= $num){
                    $result['goods_total_amount_balance'] = round((float)$goodsTotalAmount * self::balanceDiscount($user->id));
                    $result['express_fee_balance']    = '包邮';
                } else {
                    $expressFee=$address ? self::getExpressFee($address->province,$num,$total_weight) : $express->fee;
                    $result['goods_total_amount_balance'] = round($goodsTotalAmount * self::balanceDiscount($user->id),2);
                    $result['express_fee_balance']    = $expressFee;
                }
            }
            $result['balance_reduce'] = round($result['goods_total_amount'] - $result['goods_total_amount_balance'],2);
            $result['goods_total_num'] = $num;
            $result['discount_info']=self::getDiscountInfoByGoodsId($goodsIds,$num,$user->id);
        }elseif($type == 'shop_cart'){
            if(is_array($goodsIds)){
                $goodsInfoArr = array();
                $goodsTotalAmount   = 0;
                $goodsAmount        = 0;
                $goodsTotalNum      = 0;
                $goodsNum = count($goodsIds);
                $isFreeShipping = 0;
                $total_weight=0;
                //TODO sum one goods number
                $thisGoodsSumNun=[];
                $freeGoodsList=[];
                $allGoodsIds=[];
                $reduce_amount=0;
                foreach($goodsIds as $shop_cart_id){

                    /** @var ShopCart $temp */
                    $temp = ShopCart::whereId($shop_cart_id)->whereUserId($user->id)->first();
                    if ($temp) {
                        if (isset($thisGoodsSumNun['goods_id_' . $temp->goods_id])) {
                            $tmp = $thisGoodsSumNun['goods_id_' . $temp->goods_id];
                            $thisGoodsSumNun['goods_id_' . $temp->goods_id] = $tmp + $temp->num;
                        } else {
                            $thisGoodsSumNun['goods_id_' . $temp->goods_id] = $temp->num;
                        }
                        array_push($allGoodsIds,$temp->goods_id);
                    }
                }
                //TODO 遍历统计赠送（满减）数量
                $allGoodsIds=array_unique($allGoodsIds);
                if (count($allGoodsIds) > 0){
                    foreach ($allGoodsIds as $item){
                        $free_num=self::getFreeNum($item,$thisGoodsSumNun['goods_id_' . $item],$user->id);
                        $freeGoodsList['free_goods_id'.$item]=$free_num;
                        //$freeGoodsList=['free_goods_id1'=>5]
                        //$freeGoodsList=['free_goods_id*'=>送的数量]
                        $reduce_amount=$reduce_amount + self::getGoodsReduce($item,$thisGoodsSumNun['goods_id_' . $item],$user->id);
                    }
                }
                if(count($goodsIds) > 0){
                    foreach($goodsIds as $goodsId){
                        /** @var ShopCart $shopCart */
                        $shopCart = ShopCart::whereId($goodsId)->first();
                        if(!$shopCart)
                            return response()->json(['level' => 'error','message' => '该购物车商品不存在']);

                        /** @var Goods $thisGoods */
                        $thisGoods = Goods::whereId($shopCart->goods_id)->whereIsShop(1)->first();
                        if(!$thisGoods)
                            return response()->json(['level' => 'error','message' => '商品已下架']);
                        $total_weight=$total_weight+($thisGoods->weight * $shopCart->num);

                        /** @var GoodsSpu $thisGoodsSpu */
                        $thisGoodsSpu = GoodsSpu::whereId($shopCart->goods_spu_id)->whereGoodsId($thisGoods->id)->whereStatus(1)->first();
                        if(!$thisGoodsSpu)
                            return response()->json(['level' => 'error','message' => '商品属性不存在']);

                        $thisGoods->thumb_url      = FileManager::getImgUrl($thisGoods->thumb_id);
                        $thisGoods->goods_num      = $shopCart->num;
                        $thisGoods->goods_spu_info = $thisGoodsSpu;
                        $discount_info             = self::getDiscountInfoByGoodsId($thisGoods->id,$shopCart->num,$user->id);
                        $thisGoods->discount_name  = count($discount_info['name']) > 0 ? $discount_info['name'] : ['无优惠'];
                        //TODO 商品优惠
                        $discount_price=$thisGoodsSpu->price * self::getGoodsDiscount($thisGoods->id,$thisGoodsSumNun['goods_id_' . $thisGoods->id],$user->id);
                        $tmp_price =(isset($freeGoodsList['free_goods_id'.$shopCart->goods_id]) && $freeGoodsList['free_goods_id'.$shopCart->goods_id] > 0)
                            ? ($freeGoodsList['free_goods_id'.$shopCart->goods_id] >= $shopCart->num ? 0.00
                                : round($discount_price * ($shopCart->num - $freeGoodsList['free_goods_id'.$shopCart->goods_id]) / $shopCart->num,2))
                            : $discount_price;
//                        $reduce_amount= $reduce_amount + ($thisGoodsSpu->price - $thisGoods->s_price);
                        if($thisGoods->is_free_shipping == 1)
                            $isFreeShipping += 1;

                        $goodsTotalAmount += round((float)$tmp_price * (int)$shopCart->num,2);
                        $goodsAmount += round((float)$thisGoodsSpu->price * (int)$shopCart->num,2);
                        $goodsTotalNum = $goodsTotalNum + $shopCart->num;
                        array_push($goodsInfoArr,$thisGoods);

                        //TODO 减掉赠送的数量
                        if (isset($freeGoodsList['free_goods_id'.$shopCart->goods_id]) && $freeGoodsList['free_goods_id'.$shopCart->goods_id] > 0){
                            if ($freeGoodsList['free_goods_id'.$shopCart->goods_id] >= $shopCart->num){
                                $arrT=$freeGoodsList['free_goods_id'.$shopCart->goods_id];
                                $freeGoodsList['free_goods_id'.$shopCart->goods_id] = $arrT - $shopCart->num;
                            } else {
                                $freeGoodsList['free_goods_id'.$shopCart->goods_id] = 0;
                            }
                        } else {
                            $freeGoodsList['free_goods_id'.$shopCart->goods_id] = 0;
                        }
                    }
                }
                $goodsTotalAmount=$goodsTotalAmount-$reduce_amount;

                /** @var Express $express */
                $express = Express::whereIsDefault(1)->first();
                $address=UserAddress::whereId($address_id)->first();
                if(!$express)
                    return response()->json(['level' => 'error','message' => '未找到快递公司']);

                $result['express_company']    = $express->name;
                if($goodsNum == $isFreeShipping){
                    $result['express_fee']    = '包邮';
                    $result['express_fee_balance']    = '包邮';
                    $result['goods_total_amount'] =  round((float)$goodsTotalAmount,2);
                    $result['goods_total_amount_balance'] = round($goodsTotalAmount * self::balanceDiscount($user->id),2);
                }else{
                    if($express->order_free_shipping_price <= $goodsTotalAmount || $express->order_free_shipping_num <= $goodsTotalNum){
                        $result['express_fee']    = '包邮';
                        $result['goods_total_amount'] =  round((float)$goodsTotalAmount,2);
                    }else{
                        $expressFee=$address ? self::getExpressFee($address->province,$goodsTotalNum,$total_weight) : $express->fee;
                        $result['express_fee']    = $expressFee;
                        $result['goods_total_amount'] = round((float)$goodsTotalAmount ,2);
                    }

                    if ($express->order_free_shipping_price <= $goodsTotalAmount * self::balanceDiscount($user->id) || $express->order_free_shipping_num <= $num){
                        $result['goods_total_amount_balance'] = round((float)$goodsTotalAmount * self::balanceDiscount($user->id));
                        $result['express_fee_balance']    = '包邮';
                    } else {
                        $expressFee=$address ? self::getExpressFee($address->province,$num,$total_weight) : $express->fee;
                        $result['goods_total_amount_balance'] = round($goodsTotalAmount * self::balanceDiscount($user->id),2);
                        $result['express_fee_balance']    = $expressFee;
                    }

                }

                $result['goods_amount'] =  round((float)$goodsAmount,2);
//                $result['goods_total_amount_balance'] = round($result['goods_total_amount'] * self::balanceDiscount($user->id),2);
                $result['goods_total_num'] = $goodsTotalNum;
                $result['goods_info']      = $goodsInfoArr;
                $result['shop_cart'] = $goodsIds;
                $result['balance_reduce'] = round($result['goods_total_amount'] - $result['goods_total_amount_balance'],2);
                $result['discount_info']=self::getDiscountInfo($goodsIds,$user->id);
            }else{
                return response()->json(['level' => 'error','message' => '数据格式不正确','data' => $goodsIds]);
            }
        }
        else{
            return response()->json(['level' => 'error','message' => '订单类型不正确']);
        }
        $express=Express::whereIsDefault(1)->first();
        $result['express_info']=$express;
        return response()->json(['level' => 'success','message' => '获取成功','data' => $result]);
    }

    /**
     * 手动确认收货
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function confirmReceipt(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $orderNum = $request->get('order_num');

        /** @var Orders $thisOrder */
        $thisOrder = Orders::whereOrderNum($orderNum)->first();
        if(!$thisOrder)
            return response()->json(['level' => 'error','message' => '订单不存在！']);

        if($thisOrder->status != 3)
            return response()->json(['level' => 'error','message' => '订单状态不正确']);

        /** @var UserInfo $thisUserInfo */
        $thisUserInfo = UserInfo::whereUserId($thisOrder->user_id)->first();
        if(!$thisUserInfo)
            return response()->json(['level' => 'error','message' => '用户信息不存在']);

        $thisOrder->status = 4;
        $thisOrder->save();

        return response()->json(['level' => 'success','message' => '成功收货','data' => $thisOrder]);
    }

    public function changePayType(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $orderNum = $request->get('order_num');
        $pay_type = $request->get('pay_type');

        if (!$orderNum)
            return response()->json(['level'=>'error','message'=>'参数错误','date'=>[]]);
        if (!in_array($pay_type,['weixin','balance']))
            return response()->json(['level'=>'error','message'=>'支付方式不受支持','date'=>[]]);
        $thisOrder = Orders::whereOrderNum($orderNum)->first();
        if(!$thisOrder || ($thisOrder && $thisOrder->status == 6))
            return response()->json(['level' => 'error','message' => '订单不存在或已取消']);

        if ($thisOrder->user_id != $user->id)
            return response()->json(['level' => 'error','message' => '您无权修改']);

        if($thisOrder->is_pay == 1)
            return response()->json(['level' => 'error','message' => '订单已支付']);


        if($thisOrder->status == 1 && (strtotime($thisOrder->created_at) + (30 * 60)) < time()){
            $thisOrder->status = 6;
            $thisOrder->save();

            /** @var UserCoupon $thisCoupon */
            $thisCoupon = UserCoupon::whereId($thisOrder->coupon_id)->first();
            if($thisCoupon){
                $thisCoupon->is_locking = 0;
                $thisCoupon->save();
            }
            return response()->json(['level' => 'error','message' => '订单已失效']);
        }
        $thisOrder->pay_type    =$pay_type;
        $thisOrder->s_amount    =$pay_type=='balance' ? $thisOrder->b_amount : $thisOrder->w_amount;
        $thisOrder->express_fee =$pay_type=='balance' ? $thisOrder->express_fee_b : $thisOrder->express_fee_w;
        $thisOrder->save();
        /** @var OrderItem $orderItem */
        $orderItems = OrderItem::whereOrderId($thisOrder->id)->orderBy('created_at','desc')->get();
        if(count($orderItems) > 0){
            foreach($orderItems as $orderItem){
                /** @var GoodsSnapshot $thisGoods */
                $thisGoods = GoodsSnapshot::whereId($orderItem->goods_snapshot_id)->first();
                if($thisGoods){
                    $thisGoods->thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);
                }

                $thisGoodsSpu = GoodsSpu::whereId($orderItem->goods_spu_id)->whereGoodsId($orderItem->goods_id)->whereStatus(1)->first();

                $orderItem->goods_spu_info = $thisGoodsSpu;
                $orderItem->goods_info     = $thisGoods;
            }
        }

        if($thisOrder->status == 1){
            $thisOrder->statusType = '待付款';
        }elseif($thisOrder->status == 2){
            $thisOrder->statusType = '待发货';
        }elseif($thisOrder->status == 3){
            $thisOrder->statusType = '待收货';
        }elseif($thisOrder->status == 4){
            $thisOrder->statusType = '待评价';
        }elseif($thisOrder->status == 5){
            $thisOrder->statusType = '已完成';
        }elseif($thisOrder->status == 6){
            $thisOrder->statusType = '已取消';
        }elseif($thisOrder->status == 8){
            $thisOrder->statusType = '待分享';
        }

        $thisOrder->order_item = $orderItems;
        $thisOrder->discount_note = json_decode($thisOrder->discount_note);
        return response()->json(['level' => 'success','message' => '修改成功','data'=>$thisOrder]);

    }

    public function getProvinceExpressFee(Request $request){
        $province   =$request->get('province');
        $goods_id   =$request->get('goods_id');
        $num        =$request->get('num');
        $cart_ids   =$request->get('cart_ids');
        $total_weight=0.00;
        $total_num   =0;
        if (is_array($cart_ids) && count($cart_ids) > 0){
            foreach ($cart_ids as $cart_id){
                $thisCart=ShopCart::whereId($cart_id)->first();
                if ($thisCart){
                    $thisGoods=Goods::whereId($thisCart->goods_id)->first();
                    if ($thisGoods){
                        $total_weight= round($total_weight + ($thisGoods->weight * $thisCart->num),2);
                    }
                    $total_num = $total_num + $thisCart->num;
                }
            }
            $fee=self::getExpressFee($province,$total_num,$total_weight ? $total_weight : 0);
            return response()->json(['level'=>'success','message'=>'shop_cart','data'=>$fee,'total_weight'=>$total_weight]);
        } else if ($goods_id){
            $thisGoods=Goods::whereId($goods_id)->first();
            if ($thisGoods){
                $total_weight=$thisGoods->weight * $num;
            }
            $fee=self::getExpressFee($province,$num,$total_weight ? $total_weight : 0);
            return response()->json(['level'=>'success','message'=>'goods','data'=>$fee,'total_weight'=>$total_weight]);
        }
        return response()->json(['level'=>'success','message'=>'error','data'=>10000,'total_weight'=>$total_weight]);
    }

    public function orderRefundApply(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $order_num  =$request->get('order_num');
        $type       =$request->get('type');
        $desc       =$request->get('desc');
        if (!$order_num)
            return response()->json(['level' => 'error','message' => '参数错误']);

        if (!in_array($type,[1,2,3]))
            return response()->json(['level' => 'error','message' => '请选择售后类型']);
        if ($type==3){
            return response()->json(['level' => 'error','message' => '售后类型请选择“仅退款”或“退货退款”']);
        }
        $thisOrder=Orders::whereOrderNum($order_num)->first();
        if (!$thisOrder)
            return response()->json(['level' => 'error','message' => '订单不存在']);
        if ($thisOrder->user_id != $user->id)
            return response()->json(['level' => 'error','message' => '这不是当前账号的订单']);
        $refund=OrderRefund::whereOrderNum($order_num)->whereUserId($user->id)->orderBy('id','desc')->first();
        if ($refund && $refund->status != 2)
            return response()->json(['level' => 'error','message' => '售后处理中或处理完成']);
        $thisOrder->status=7;
        $thisOrder->save();

        $newRefund=new OrderRefund();
        $newRefund->order_num=$order_num;
        $newRefund->user_id =$user->id;
        $newRefund->type    =$type;
        $newRefund->desc    =$desc;
        $newRefund->save();
        return response()->json(['level' => 'success','message' => '已提交售后申请']);

    }

    public function orderRefundExpress(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $order_num  =$request->get('order_num');
        $express_num=$request->get('express_num');
        $express_company=$request->get('express_company');
        if (!$express_num)
            return response()->json(['level'=>'error','message'=>'请输入快递单号']);
        if (!$express_company)
            return response()->json(['level'=>'error','message'=>'请输入快递公司名']);
        /** @var OrderRefund $thisRefund */
        $thisRefund=OrderRefund::whereOrderNum($order_num)->whereUserId($user->id)->orderBy('id','desc')->first();
        if (!$thisRefund)
            return response()->json(['level' => 'error','message' => '该订单没有申请售后，无需填写']);
        if ($thisRefund->type == 1)
            return response()->json(['level' => 'error','message' => '该订单不需要填写单号']);
        if ($thisRefund->status != 1)
            return response()->json(['level' => 'error','message' => '目前不能填写返货单号']);
        if ($thisRefund->express_num !='')
            return response()->json(['level' => 'error','message' => '已填写单号']);
        $thisRefund->express_company=$express_company ? $express_company : '';
        $thisRefund->express_num    =$express_num ? $express_num : '';
        $thisRefund->save();
        return response()->json(['level'=>'success','message'=>'已成功填写快递单号']);
    }
    public function getReturnInfo(Request $request){
        $address=ReturnAddress::first();
        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$address]);
    }

    /**
     * 获取折扣率
     * @param $user_id
     * @return bool|float|mixed
     */
    public static function balanceDiscount($user_id){
        if ($user_id==0)
            return 1;

        $user_rule=ChargeAvailable::whereUserId($user_id)->first();
        if (!$user_rule)
            return 1;

        if(!$user_rule->discount_rule_id)
            return 1;

        $rule=DiscountRule::whereId($user_rule->discount_rule_id)->first();
        if (!$rule)
            return 1;

        if (0 < $rule->rate && $rule->rate <=1)
            return $rule->rate;

        return 1;
    }

    /**
     * 获取商品的赠送数量
     * @param $goods_id
     * @param int $num
     * @param int $user_id
     * @return float|int
     */
    private static function getGoodsFreeNum($goods_id,$num=1,$user_id=0){
        $isVip=self::isVip($user_id);
        $goods_rules=DiscountXGoods::whereGoodsId($goods_id)->pluck('discount_sales_rule_id')->toArray();
        if (count($goods_rules) > 0){
            $freeRules=DiscountSalesRule::whereType('buy_get_free')->whereIn('id',$goods_rules)->whereStatus(1)->orderBy('satisfy_number','desc')->get();
            if (count($freeRules) > 0){
                /** @var DiscountSalesRule $rule */
                foreach ($freeRules as $rule){
                    if ($rule->range=='vip' && $isVip){
                        if (!is_null($rule->start_time) && !is_null($rule->end_time)){
                            if (strtotime($rule->start_time) <= time() && time() < strtotime($rule->end_time)){
                                if ($num >= $rule->satisfy_number){
                                    return $rule->free_get_number * intval($num/$rule->satisfy_number);
                                }
                            }
                        } else {
                            if ($num >= $rule->satisfy_number){
                                return $rule->free_get_number * intval($num/$rule->satisfy_number);
                            }
                        }
                    } elseif ($rule->range=='all'){
                        if (!is_null($rule->start_time) && !is_null($rule->end_time)){
                            if (strtotime($rule->start_time) <= time() && time() < strtotime($rule->end_time)){
                                if ($num >= $rule->satisfy_number){
                                    return $rule->free_get_number * intval($num/$rule->satisfy_number);
                                }
                            }
                        } else {
                            if ($num >= $rule->satisfy_number){
                                return $rule->free_get_number * intval($num/$rule->satisfy_number);
                            }
                        }
                    }

                }
            }
        }
        return 0;
    }

    private static function getFreeNum($goods_id,$num=1,$user_id=0){
        $isVip=self::isVip($user_id);
        $goods_rules=DiscountXGoods::whereGoodsId($goods_id)->pluck('discount_sales_rule_id')->toArray();
        if (count($goods_rules) > 0){
            $freeRules=DiscountSalesRule::whereType('buy_get_free')->whereIn('id',$goods_rules)->whereStatus(1)->orderBy('satisfy_number','desc')->get();
            if (count($freeRules) > 0){
                /** @var DiscountSalesRule $rule */
                foreach ($freeRules as $rule){
                    if ($rule->range=='vip' && $isVip){
                        if (!is_null($rule->start_time) && !is_null($rule->end_time)){
                            if (strtotime($rule->start_time) <= time() && time() < strtotime($rule->end_time)){
                                if ($num >= $rule->satisfy_number){
                                    //买的数量包括赠送的量
                                    //  return 送M                    * 去零取整（下单数量/（买N+送M））
                                    return $rule->free_get_number * intval($num/($rule->satisfy_number + $rule->free_get_number));
//                                return $rule->free_get_number * intval($num/$rule->satisfy_number);
                                }
                            }
                        } else {
                            if ($num >= $rule->satisfy_number){
                                return $rule->free_get_number * intval($num/$rule->satisfy_number);
                            }
                        }
                    } elseif ($rule->range=='all'){
                        if (!is_null($rule->start_time) && !is_null($rule->end_time)){
                            if (strtotime($rule->start_time) <= time() && time() < strtotime($rule->end_time)){
                                if ($num >= $rule->satisfy_number){
                                    //买的数量包括赠送的量
                                    //  return 送M                    * 去零取整（下单数量/（买N+送M））
                                    return $rule->free_get_number * intval($num/($rule->satisfy_number + $rule->free_get_number));
//                                return $rule->free_get_number * intval($num/$rule->satisfy_number);
                                }
                            }
                        } else {
                            if ($num >= $rule->satisfy_number){
                                return $rule->free_get_number * intval($num/$rule->satisfy_number);
                            }
                        }
                    }



                }
            }
        }
        return 0;
    }

    /**
     * 获取商品的折扣
     * @param $goods_id
     * @param int $num
     * @param int $user_id
     * @return float|int
     */
    private static function getGoodsDiscount($goods_id,$num=1,$user_id=0){
//        $time=date('Y-m-d H:i:s',time());
        $goods_rules=DiscountXGoods::whereGoodsId($goods_id)->pluck('discount_sales_rule_id')->toArray();
        $isVip=self::isVip($user_id);
        if (count($goods_rules) > 0){
            $freeRules=DiscountSalesRule::whereType('discount')->whereIn('id',$goods_rules)->whereStatus(1)->orderBy('satisfy_number','desc')->get();
            if (count($freeRules) > 0){
                /** @var DiscountSalesRule $rule */
                foreach ($freeRules as $rule){
                    if ($rule->range=='vip' && $isVip){
                        if (!is_null($rule->start_time) && !is_null($rule->end_time)){
                            if (strtotime($rule->start_time) <= time() && time() < strtotime($rule->end_time)){
                                if ($num >= $rule->satisfy_number){
                                    return $rule->reduce_rate;
                                }
                            }
                        } else{
                            if ($num >= $rule->satisfy_number){
                                return $rule->reduce_rate;
                            }
                        }
                    } else if ($rule->range=='all'){
                        if (!is_null($rule->start_time) && !is_null($rule->end_time)){
                            if (strtotime($rule->start_time) <= time() && time() < strtotime($rule->end_time)){
                                if ($num >= $rule->satisfy_number){
                                    return $rule->reduce_rate;
                                }
                            }
                        } else{
                            if ($num >= $rule->satisfy_number){
                                return $rule->reduce_rate;
                            }
                        }
                    }
//                    if (!is_null($rule->start_time) && !is_null($rule->end_time)){
//                        if (strtotime($rule->start_time) <= time() && time() < strtotime($rule->end_time)){
//                            if ($num >= $rule->satisfy_number){
//                                return $rule->reduce_rate;
//                            }
//                        }
//                    } else{
//                        if ($num >= $rule->satisfy_number){
//                            return $rule->reduce_rate;
//                        }
//                    }


                }
            }
        }
        return 1;
    }

    /**
     * 获取商品的满减优惠金额
     * @param $goods_id
     * @param int $total_num
     * @param int $user_id
     * @return float|int
     */
    private static function getGoodsReduce($goods_id,$total_num=1,$user_id=0){
        $isVip=self::isVip($user_id);
        $goods_rules=DiscountXGoods::whereGoodsId($goods_id)->pluck('discount_sales_rule_id')->toArray();
        if (count($goods_rules) > 0){
            $freeRules=DiscountSalesRule::whereType('reduce')->whereIn('id',$goods_rules)->whereStatus(1)->orderBy('satisfy_number','desc')->get();
            if (count($freeRules) > 0){
                /** @var DiscountSalesRule $rule */
                foreach ($freeRules as $rule){
                    if ($rule->range=='vip' && $isVip){
                        if (!is_null($rule->start_time) && !is_null($rule->end_time)){
                            if (strtotime($rule->start_time) <= time() && time() < strtotime($rule->end_time)){
                                if ($total_num >= $rule->satisfy_number){
                                    return $rule->reduce_amount;
                                }
                            }
                        } else {
                            if ($total_num >= $rule->satisfy_number){
                                return $rule->reduce_amount;
                            }
                        }
                    } else if ($rule->range=='all'){
                        if (!is_null($rule->start_time) && !is_null($rule->end_time)){
                            if (strtotime($rule->start_time) <= time() && time() < strtotime($rule->end_time)){
                                if ($total_num >= $rule->satisfy_number){
                                    return $rule->reduce_amount;
                                }
                            }
                        } else {
                            if ($total_num >= $rule->satisfy_number){
                                return $rule->reduce_amount;
                            }
                        }
                    }


                }
            }
        }
        return 0;
    }

    /**
     * 计算运费
     * @param $province
     * @param int $total_num
     * @param int $total_weight
     * @return float|int
     */
    private static function getExpressFee($province,$total_num=1,$total_weight=0){
        $province=substr($province,0,6);
        $userFee=0.00;
        $total_weight=$total_weight ? round($total_weight) : round($total_num * 0.3,2);
        //TODO 检查自定义运费模板
        $custom_default=ExpressBlade::whereIsDefault(1)->first();
        if ($custom_default){
            /** @var ExpressCustomFee $thisBladeRule */
            $thisBladeRule=ExpressCustomFee::whereExpressBladeId($custom_default->id)
                ->where('province','like',$province.'%')
                ->orderBy('id','desc')
                ->first();
            if ($thisBladeRule){
                $userFee=$userFee+$thisBladeRule->first_price;
                if ($total_weight-$thisBladeRule->first_weight > 0){
                    $userFee=$userFee + (ceil(($total_weight-$thisBladeRule->first_weight) / $thisBladeRule->next_weight) * $thisBladeRule->next_price);
                }
                return round($userFee,2);
            } else {
                $all=ExpressCustomFee::whereExpressBladeId($custom_default->id)
                    ->whereProvince('全国')
                    ->orderBy('id','desc')
                    ->first();
                if ($all){
                    $userFee=$userFee+$thisBladeRule->first_price;
                    if ($total_weight-$thisBladeRule->first_weight > 0){
                        $userFee=$userFee + (ceil(($total_weight-$thisBladeRule->first_weight) / $thisBladeRule->next_weight) * $thisBladeRule->next_price);
                    }
                    return round($userFee,2);
                }
            }
        }
        $fee=0;
        $weight=round($total_num * 0.3,2);
        //TODO 默认运费
        $fee_6  =['广东','上海','浙江','江苏','福建','广西','安徽','江西','湖南','湖北','山东','河北','河南','北京','天津','重庆','四川','贵州','云南','海南','山西','陕西','辽宁','吉林','黑龙'];
        $fee_14 =['青海','甘肃','内蒙','宁夏','新疆','西藏'];
        $add_1  =['广东'];
        $add_4  =['上海','浙江','江苏','福建','广西','安徽','江西','湖南','湖北'];
        $add_5  =['山东','河北','河南','北京','天津','重庆','四川','贵州','云南','海南','云南','海南'];
        $add_6  =['山西','陕西','辽宁','吉林','黑龙'];
        $add_11 =['青海','甘肃','内蒙','宁夏'];
        $add_12 =['新疆','西藏'];
        //首重
        if (in_array($province,$fee_6)){
            $fee=$fee+6;
        }
        if (in_array($province,$fee_14)){
            $fee=$fee+14;
        }
        //续重
        if ($weight-1.5 > 0){
            if (in_array($province,$add_1))
                $fee=$fee + (ceil($weight-1.5) * 1);
            if (in_array($province,$add_4))
                $fee=$fee + (ceil($weight-1.5) * 4);
            if (in_array($province,$add_5))
                $fee=$fee + (ceil($weight-1.5) * 5);
            if (in_array($province,$add_6))
                $fee=$fee + (ceil($weight-1.5) * 6);
            if (in_array($province,$add_11))
                $fee=$fee + (ceil($weight-1.5) * 11);
            if (in_array($province,$add_12))
                $fee=$fee + (ceil($weight-1.5) * 12);
        }
        if ($fee)
            return $fee;
        else
            return 1000000;
    }

    private static function getDiscountInfo($cart_ids,$user_id){
        //TODO sum one goods number
        $thisGoodsSumNun=[];
        $allGoodsIds=[];//所有的商品的id
        $discount_info=[
            'name'=>[],
            'reduce'=>0.00
        ];
        $isVip=self::isVip($user_id);

        if (count($cart_ids) > 0){
            foreach($cart_ids as $shop_cart_id){
                /** @var ShopCart $temp */
                $temp = ShopCart::whereId($shop_cart_id)->whereUserId($user_id)->first();
                if ($temp) {
                    if (isset($thisGoodsSumNun['goods_id_' . $temp->goods_id])) {
                        $tmp = $thisGoodsSumNun['goods_id_' . $temp->goods_id];
                        $thisGoodsSumNun['goods_id_' . $temp->goods_id] = $tmp + $temp->num;
                    } else {
                        $thisGoodsSumNun['goods_id_' . $temp->goods_id] = $temp->num;
                    }
                    array_push($allGoodsIds,$temp->goods_id);
                }
            }
            $allGoodsIds=array_unique($allGoodsIds);
//            $time=date('Y-m-d H:i:s',time());
            if (count($allGoodsIds) > 0){
                foreach ($allGoodsIds as $goods_id){
                    $thisGoods=Goods::whereId($goods_id)->whereIsShop(1)->first();
                    if ($thisGoods){
                        $goods_rules=DiscountXGoods::whereGoodsId($goods_id)->pluck('discount_sales_rule_id')->toArray();
                        if (count($goods_rules) > 0){
                            //TODO 统计赠送
                            $freeRules=DiscountSalesRule::whereType('buy_get_free')->whereIn('id',$goods_rules)->whereStatus(1)->orderBy('satisfy_number','desc')->get();
                            if (count($freeRules) > 0){
                                /** @var DiscountSalesRule $rule */
                                foreach ($freeRules as $rule){
                                    if ($rule->range=='vip' && $isVip){
                                        if (!is_null($rule->start_time) && !is_null($rule->end_time)){
                                            if (strtotime($rule->start_time) <= time() && time() < strtotime($rule->end_time)){
                                                if ($thisGoodsSumNun['goods_id_' . $goods_id] >= $rule->satisfy_number){
                                                    array_push($discount_info['name'],$rule->name);
                                                    $reduce_temp=$discount_info['reduce'];
                                                    $discount_info['reduce']=$reduce_temp + ($thisGoods->s_price * ($rule->free_get_number * intval($thisGoodsSumNun['goods_id_' . $goods_id]/($rule->satisfy_number + $rule->free_get_number))));
                                                }
                                            }
                                        } else {
                                            if ($thisGoodsSumNun['goods_id_' . $goods_id] >= $rule->satisfy_number){
                                                array_push($discount_info['name'],$rule->name);
                                                $reduce_temp=$discount_info['reduce'];
                                                $discount_info['reduce']=$reduce_temp + ($thisGoods->s_price * ($rule->free_get_number * intval($thisGoodsSumNun['goods_id_' . $goods_id]/($rule->satisfy_number + $rule->free_get_number))));

                                            }
                                        }
                                    } elseif ($rule->range=='all'){
                                        if (!is_null($rule->start_time) && !is_null($rule->end_time)){
                                            if (strtotime($rule->start_time) <= time() && time() < strtotime($rule->end_time)){
                                                if ($thisGoodsSumNun['goods_id_' . $goods_id] >= $rule->satisfy_number){
                                                    array_push($discount_info['name'],$rule->name);
                                                    $reduce_temp=$discount_info['reduce'];
                                                    $discount_info['reduce']=$reduce_temp + ($thisGoods->s_price * ($rule->free_get_number * intval($thisGoodsSumNun['goods_id_' . $goods_id]/($rule->satisfy_number + $rule->free_get_number))));
                                                }
                                            }
                                        } else {
                                            if ($thisGoodsSumNun['goods_id_' . $goods_id] >= $rule->satisfy_number){
                                                array_push($discount_info['name'],$rule->name);
                                                $reduce_temp=$discount_info['reduce'];
                                                $discount_info['reduce']=$reduce_temp + ($thisGoods->s_price * ($rule->free_get_number * intval($thisGoodsSumNun['goods_id_' . $goods_id]/($rule->satisfy_number + $rule->free_get_number))));

                                            }
                                        }
                                    }


                                    //end foreach ($freeRules as $rule)
                                }
                            }

                            //TODO 统计打折
                            $discount_rule=DiscountSalesRule::whereType('discount')->whereIn('id',$goods_rules)->whereStatus(1)->orderBy('satisfy_number','desc')->get();
                            if (count($discount_rule) > 0){
                                /** @var DiscountSalesRule $rule */
                                foreach ($discount_rule as $rule){
                                    if (!is_null($rule->start_time) && !is_null($rule->end_time)){
                                        if (strtotime($rule->start_time) <= time() && time() < strtotime($rule->end_time)){
                                            if ($thisGoodsSumNun['goods_id_' . $goods_id] >= $rule->satisfy_number){
                                                //打折的优惠活动
                                                array_push($discount_info['name'],$rule->name);
                                                $reduce_temp=$discount_info['reduce'];
                                                $discount_info['reduce']=$reduce_temp + ($thisGoods->s_price * $thisGoodsSumNun['goods_id_' . $goods_id] * ( 1 - $rule->reduce_rate));
                                            }
                                        }
                                    } else {
                                        if ($thisGoodsSumNun['goods_id_' . $goods_id] >= $rule->satisfy_number){
//                                      //打折的优惠活动
                                            array_push($discount_info['name'],$rule->name);
                                            $reduce_temp=$discount_info['reduce'];
                                            $discount_info['reduce']=$reduce_temp + ($thisGoods->s_price * $thisGoodsSumNun['goods_id_' . $goods_id] * ( 1 - $rule->reduce_rate));
                                        }
                                    }

                                    //end foreach ($freeRules as $rule)
                                }
                            }

                            $reduce_rule=DiscountSalesRule::whereType('reduce')->whereIn('id',$goods_rules)->whereStatus(1)->orderBy('satisfy_number','desc')->get();
                            if (count($reduce_rule) > 0){
                                /** @var DiscountSalesRule $rule */
                                foreach ($reduce_rule as $rule){
                                    if (!is_null($rule->start_time) && !is_null($rule->end_time)){
                                        if (strtotime($rule->start_time) <= time() && time() < strtotime($rule->end_time)){
                                            if ($thisGoodsSumNun['goods_id_' . $goods_id] >= $rule->satisfy_number){
                                                //满减的优惠活动
                                                array_push($discount_info['name'],$rule->name);
                                                $reduce_temp=$discount_info['reduce'];
                                                $discount_info['reduce']=$reduce_temp + $rule->reduce_amount;
                                            }
                                        }
                                    } else {
                                        if ($thisGoodsSumNun['goods_id_' . $goods_id] >= $rule->satisfy_number){
//                                      //满减的优惠活动
                                            array_push($discount_info['name'],$rule->name);
                                            $reduce_temp=$discount_info['reduce'];
                                            $discount_info['reduce']=$reduce_temp + $rule->reduce_amount;
                                        }
                                    }

                                    //end foreach ($freeRules as $rule)
                                }
                            }
                        }
                    }

                    //end  foreach ($allGoodsIds as $goods_id)
                }

            }
        }

        $fol=$discount_info['reduce'];
        $discount_info['reduce']=round($fol,2);
        $discount_info['name']=array_unique($discount_info['name']);
        return $discount_info;

    }
    private static function getDiscountInfoByGoodsId($goods_id,$num,$user_id=0){
        $discount_info=[
            'name'=>[],
            'reduce'=>0.00
        ];
        $isVip=self::isVip($user_id);
        $thisGoods=Goods::whereId($goods_id)->whereIsShop(1)->first();
        if ($thisGoods) {
            $goods_rules = DiscountXGoods::whereGoodsId($goods_id)->pluck('discount_sales_rule_id')->toArray();
            if (count($goods_rules) > 0) {
                //TODO 赠送
                $freeRules = DiscountSalesRule::whereType('buy_get_free')->whereIn('id',$goods_rules)->whereStatus(1)->orderBy('satisfy_number', 'desc')->get();
                if (count($freeRules) > 0) {
                    /** @var DiscountSalesRule $rule */
                    foreach ($freeRules as $rule) {
                        if ($rule->range=='vip' && $isVip){
                            if (!is_null($rule->start_time) && !is_null($rule->end_time)) {
                                if (strtotime($rule->start_time) <= time() && time() < strtotime($rule->end_time)){
                                    if ($num >= $rule->satisfy_number) {
//                                        return $rule->free_get_number * intval($num/$rule->satisfy_number);
                                        //赠送的优惠活动
                                        array_push($discount_info['name'], $rule->name);
                                    }
                                }
                            } else {
                                if ($num >= $rule->satisfy_number) {
//                                    return $rule->free_get_number * intval($thisGoodsSumNun['goods_id_' . $goods_id]/$rule->satisfy_number);
                                    array_push($discount_info['name'], $rule->name);
                                }
                            }
                        } else if ($rule->range=='all'){
                            if (!is_null($rule->start_time) && !is_null($rule->end_time)) {
                                if (strtotime($rule->start_time) <= time() && time() < strtotime($rule->end_time)){
                                    if ($num >= $rule->satisfy_number) {
//                                        return $rule->free_get_number * intval($num/$rule->satisfy_number);
                                        //赠送的优惠活动
                                        array_push($discount_info['name'], $rule->name);
                                    }
                                }
                            } else {
                                if ($num >= $rule->satisfy_number) {
//                                    return $rule->free_get_number * intval($thisGoodsSumNun['goods_id_' . $goods_id]/$rule->satisfy_number);
                                    array_push($discount_info['name'], $rule->name);
                                }
                            }

                        }

                        //end foreach ($freeRules as $rule)
                    }
                }
                //TODO 打折
                $discount_rule = DiscountSalesRule::whereType('discount')->whereIn('id',$goods_rules)->whereStatus(1)->orderBy('satisfy_number', 'desc')->get();
                if (count($discount_rule) > 0) {
                    /** @var DiscountSalesRule $rule */
                    foreach ($discount_rule as $rule) {
                        if ($rule->range=='vip' && $isVip){
                            if (!is_null($rule->start_time) && !is_null($rule->end_time)) {
                                if (strtotime($rule->start_time) <= time() && time() < strtotime($rule->end_time)){
                                    if ($num >= $rule->satisfy_number) {
                                        //打折的优惠活动
                                        array_push($discount_info['name'], $rule->name);
                                        $reduce_temp = $discount_info['reduce'];
                                        $discount_info['reduce'] = $reduce_temp + ($thisGoods->s_price * $num * (1 - $rule->reduce_rate));
                                    }
                                }
                            } else {
                                if ($num >= $rule->satisfy_number) {
//                                      //打折的优惠活动
                                    array_push($discount_info['name'], $rule->name);
                                    $reduce_temp = $discount_info['reduce'];
                                    $discount_info['reduce'] = $reduce_temp + ($thisGoods->s_price * $num * (1 - $rule->reduce_rate));
                                }
                            }
                        } elseif ($rule->range=='all'){
                            if (!is_null($rule->start_time) && !is_null($rule->end_time)) {
                                if (strtotime($rule->start_time) <= time() && time() < strtotime($rule->end_time)){
                                    if ($num >= $rule->satisfy_number) {
                                        //打折的优惠活动
                                        array_push($discount_info['name'], $rule->name);
                                        $reduce_temp = $discount_info['reduce'];
                                        $discount_info['reduce'] = $reduce_temp + ($thisGoods->s_price * $num * (1 - $rule->reduce_rate));
                                    }
                                }
                            } else {
                                if ($num >= $rule->satisfy_number) {
//                                      //打折的优惠活动
                                    array_push($discount_info['name'], $rule->name);
                                    $reduce_temp = $discount_info['reduce'];
                                    $discount_info['reduce'] = $reduce_temp + ($thisGoods->s_price * $num * (1 - $rule->reduce_rate));
                                }
                            }
                        }


                        //end foreach ($freeRules as $rule)
                    }
                }
                //TODO 满减
                $reduce_rule = DiscountSalesRule::whereType('reduce')->whereIn('id',$goods_rules)->whereStatus(1)->orderBy('satisfy_number', 'desc')->get();
                if (count($reduce_rule) > 0) {
                    /** @var DiscountSalesRule $rule */
                    foreach ($reduce_rule as $rule) {
                        if ($rule->range=='vip' && $isVip){
                            if (!is_null($rule->start_time) && !is_null($rule->end_time)) {
                                if (strtotime($rule->start_time) <= time() && time() < strtotime($rule->end_time)){
                                    if ($num >= $rule->satisfy_number) {
                                        //满减的优惠活动
                                        array_push($discount_info['name'], $rule->name);
                                        $reduce_temp = $discount_info['reduce'];
                                        $discount_info['reduce'] = $reduce_temp + $rule->reduce_amount;
                                    }
                                }
                            } else {
                                if ($num >= $rule->satisfy_number) {
//                                      //满减的优惠活动
                                    array_push($discount_info['name'], $rule->name);
                                    $reduce_temp = $discount_info['reduce'];
                                    $discount_info['reduce'] = $reduce_temp + $rule->reduce_amount;
                                }
                            }
                        } elseif ($rule->range=='all'){
                            if (!is_null($rule->start_time) && !is_null($rule->end_time)) {
                                if (strtotime($rule->start_time) <= time() && time() < strtotime($rule->end_time)){
                                    if ($num >= $rule->satisfy_number) {
                                        //满减的优惠活动
                                        array_push($discount_info['name'], $rule->name);
                                        $reduce_temp = $discount_info['reduce'];
                                        $discount_info['reduce'] = $reduce_temp + $rule->reduce_amount;
                                    }
                                }
                            } else {
                                if ($num >= $rule->satisfy_number) {
//                                      //满减的优惠活动
                                    array_push($discount_info['name'], $rule->name);
                                    $reduce_temp = $discount_info['reduce'];
                                    $discount_info['reduce'] = $reduce_temp + $rule->reduce_amount;
                                }
                            }
                        }
                        //end foreach ($freeRules as $rule)
                    }
                }
            }
        }
        $fol=$discount_info['reduce'];
        $discount_info['reduce']=round($fol,2);
        $discount_info['name']=array_unique($discount_info['name']);
        return $discount_info;

    }
    protected static function isVip($user_id){
        if ($user_id==0)
            return false;
        $vip=ChargeAvailable::whereUserId($user_id)->first();
        if ($vip)
            return true;
        else
            return false;
    }

}
